<template>
  <view class="detail-page">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="nav-back" @click="goBack">
        <text class="nav-icon">←</text>
      </view>
      <view class="nav-title">图片详情</view>
      <view class="nav-actions">
        <view class="nav-btn" @click="toggleFavorite">
          <text class="nav-icon">{{ isFavorite ? '❤️' : '🤍' }}</text>
        </view>
      </view>
    </view>
    
    <view class="image-container" v-if="imageDetail">
      <image 
        :src="imageDetail.image" 
        mode="widthFix"
        class="detail-image"
        @load="onImageLoad"
        @error="onImageError"
      />
    </view>
    <view class="loading" v-else>
      <text>加载中...</text>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-actions" v-if="imageDetail">
      <view class="action-btn" @click="toggleFavorite">
        <text class="action-icon">{{ isFavorite ? '❤️' : '🤍' }}</text>
        <text class="action-text">{{ isFavorite ? '已收藏' : '收藏' }}</text>
      </view>
      <view class="action-btn primary" @click="downloadImage">
        <text class="action-icon">⬇️</text>
        <text class="action-text">下载高清</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useImageStore } from '@/stores/image'
import { useUserStore } from '@/stores/user'
import { getImageDetail } from '@/api/image'
import { addFavorite as addFavoriteApi, removeFavorite as removeFavoriteApi, checkFavorite } from '@/api/favorite'
import { showInterstitialAd, showRewardVideoAd } from '@/utils/ad-manager'

const imageStore = useImageStore()
const userStore = useUserStore()
const imageDetail = ref(null)
const imageId = ref('')

const isFavorite = ref(false)

// 检查收藏状态
function checkFavoriteStatus() {
  if (imageDetail.value) {
    checkFavorite(imageDetail.value.id).then(status => {
      isFavorite.value = status
    }).catch(err => {
      console.error('检查收藏状态失败:', err)
      // 失败时使用本地状态
      isFavorite.value = imageStore.isFavorite(imageDetail.value.id)
    })
  }
}

onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  imageId.value = currentPage.options.id || '1'
  
  loadImageDetail()
  
  // 进入详情页时显示插屏广告
  setTimeout(() => {
    showInterstitialAd()
  }, 1000)
})

function loadImageDetail() {
  getImageDetail(imageId.value).then(res => {
    if (res.code === 200 && res.data) {
      imageDetail.value = res.data
      // 记录浏览历史（本地和服务器）
      imageStore.addViewHistory(imageDetail.value)
      // 异步调用API记录到服务器（不阻塞页面加载）
      import('@/api/history').then(historyApi => {
        historyApi.addViewHistory(imageDetail.value.id).catch(err => {
          console.warn('记录浏览历史到服务器失败:', err)
        })
      })
      // 检查收藏状态
      checkFavoriteStatus()
    }
  }).catch(err => {
    console.error('加载图片详情失败:', err)
    uni.showToast({
      title: err.message || '加载失败',
      icon: 'none'
    })
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  })
}

function goBack() {
  uni.navigateBack()
}

function toggleFavorite() {
  if (!imageDetail.value) return
  
  // 确保已登录
  if (!userStore.isLoggedIn) {
    // 尝试登录
    // #ifdef H5
    userStore.loginAsGuest().then(() => {
      // 登录成功后重试
      toggleFavorite()
    }).catch(err => {
      console.error('登录失败:', err)
      uni.showToast({
        title: '登录失败，请稍后重试',
        icon: 'none'
      })
    })
    // #endif
    // #ifdef MP-WEIXIN
    userStore.loginWithWeixin().then(() => {
      // 登录成功后重试
      toggleFavorite()
    }).catch(err => {
      console.error('登录失败:', err)
      uni.showToast({
        title: '登录失败，请稍后重试',
        icon: 'none'
      })
    })
    // #endif
    return
  }
  
  if (isFavorite.value) {
    // 取消收藏
    removeFavoriteApi(imageDetail.value.id).then(() => {
      isFavorite.value = false
      imageStore.removeFavorite(imageDetail.value.id)
      uni.showToast({
        title: '已取消收藏',
        icon: 'success'
      })
    }).catch(err => {
      console.error('取消收藏失败:', err)
      uni.showToast({
        title: err.message || '操作失败',
        icon: 'none'
      })
    })
  } else {
    // 添加收藏
    addFavoriteApi(imageDetail.value.id).then(() => {
      isFavorite.value = true
      imageStore.addFavorite(imageDetail.value)
      uni.showToast({
        title: '收藏成功',
        icon: 'success'
      })
    }).catch(err => {
      console.error('添加收藏失败:', err)
      uni.showToast({
        title: err.message || '操作失败',
        icon: 'none'
      })
    })
  }
}

function downloadImage() {
  if (!imageDetail.value) return
  
  // 下载需要看激励视频广告
  showRewardVideoAd(() => {
    // 下载图片
    uni.downloadFile({
      url: imageDetail.value.image,
      success: (res) => {
        if (res.statusCode === 200) {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              uni.showToast({
                title: '保存成功',
                icon: 'success'
              })
            },
            fail: () => {
              uni.showToast({
                title: '保存失败',
                icon: 'none'
              })
            }
          })
        }
      },
      fail: () => {
        uni.showToast({
          title: '下载失败',
          icon: 'none'
        })
      }
    })
  })
}

function onImageLoad() {
  console.log('图片加载成功')
}

function onImageError() {
  uni.showToast({
    title: '图片加载失败',
    icon: 'none'
  })
}
</script>

<style scoped>
.detail-page {
  min-height: 100vh;
  background-color: #000;
  padding-bottom: 120rpx;
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.8), transparent);
  z-index: 100;
  padding-top: calc(20rpx + env(safe-area-inset-top));
}

.nav-back,
.nav-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-icon {
  font-size: 40rpx;
  color: #fff;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  color: #fff;
  font-weight: 500;
}

.nav-actions {
  display: flex;
  align-items: center;
}

.image-container {
  width: 100%;
  margin-top: calc(80rpx + env(safe-area-inset-top));
}

.detail-image {
  width: 100%;
  display: block;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  color: #fff;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 20rpx 30rpx;
  background-color: rgba(0, 0, 0, 0.8);
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  z-index: 100;
}

.action-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  margin: 0 10rpx;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 10rpx;
}

.action-btn.primary {
  background-color: #007aff;
}

.action-icon {
  font-size: 40rpx;
  margin-bottom: 10rpx;
}

.action-text {
  font-size: 24rpx;
  color: #fff;
}
</style>
